package codeRandomThoughts.Test39组合总和;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    List<Integer> path = new ArrayList<>();
    List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        int sum = 0;
        int startIndex = 0;
        //求和问题中,排序加上剪枝很常用,能节省不少时间
        Arrays.sort(candidates);
        backtracking(candidates, target, sum, startIndex);
        return result;
    }

    public void backtracking(int[] candidates, int target, int sum, int startIndex) {
        //终止条件
        if (sum == target) {
            result.add(new ArrayList<>(path));
            return;
        } else if (sum > target) {
            //此时永远不可能有合法解
            return;
        }

        //单层搜索
        for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
            sum += candidates[i];
            path.add(candidates[i]);
            backtracking(candidates, target, sum, i);
            path.remove(path.size() - 1);
            sum -= candidates[i];
        }
    }
}
